package com.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.reggie.common.ResultResponseVo;
import com.reggie.common.enums.backend.EmployeeEnum;
import com.reggie.common.enums.front.UserEnum;
import com.reggie.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.reggie.common.Constant.LOGIN_SESSION;
import static com.reggie.common.Constant.USER_SESSION;

/**
 * @Author 早睡蛋
 * @Date 2022/9/19 15:54:12
 * @Desc: 登录过滤器，判断用户是否已经登录
 */

@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器（支持通配符）
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    //不需要处理的路径

    private static String[] urls = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/doc.html/**",
            "/webjars/**",
            "/swagger-resources/**",
            "/favicon.ico",
            "/service-worker.js",
            "/v2/api-docs",
            "/dishImages/**",
            "/setmealImages/**",
            "/msm/sendMsm",
            "/login/**"
    };


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;

        String requestURI = request1.getRequestURI();
        log.info("拦截到请求：{}", request1.getRequestURI());

        boolean check = check(urls, requestURI);
        if (check) {
            log.info("请求{}不需要处理", request1.getRequestURI());
            chain.doFilter(request1, response1);
            return;
        }
        if (request1.getSession().getAttribute(LOGIN_SESSION) != null) {
            log.info("用户已经登录，id:{}", request1.getSession().getAttribute(LOGIN_SESSION));
            Long empId = (Long) request1.getSession().getAttribute(LOGIN_SESSION);
            BaseContext.setCurrentId(empId);
            chain.doFilter(request1, response1);
            return;
        }
        if (request1.getSession().getAttribute(USER_SESSION) != null) {
            log.info("用户已经登录，id:{}", request1.getSession().getAttribute(USER_SESSION));
            Long userId = (Long) request1.getSession().getAttribute(USER_SESSION);
            BaseContext.setCurrentId(userId);
            chain.doFilter(request1, response1);
            return;
        }
        log.info("未登录");
        response1.getWriter().write(JSON.toJSONString(UserEnum.NO_LOGIN.getResultResponseVo().setMessage("未登录")));
        return;

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    /**
     * 检查请求是否需要放行
     *
     * @param urls
     * @param requestURL
     * @return
     */
    public boolean check(String[] urls, String requestURL) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURL);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
